package com.itcast.flink.exactly;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * 采用JDBC方式向MySQL数据库写入数据，考虑事务性写入，手动编程
 *
 * 注册驱动
 * 获取连接
 * 获取预编译对象
 * 执行sql
 * 处理结果集
 * 关闭资源
 * @author lilulu
 */
public class MysqlJdbcDemo {
    public static void main(String[] args) throws Exception {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://node1:3306/?useSSL=false", "root", "123456");
            //开启事务
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement("insert into db_flink.t_student values(?,?,?)");
            preparedStatement.setInt(1, 22);
            preparedStatement.setString(2, "jack");
            preparedStatement.setInt(3,25);
            preparedStatement.execute();
            //事务提交
            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (null != connection) {
                //事务回滚
                connection.rollback();
            }
        } finally {
            if (null != preparedStatement) {
                preparedStatement.close();
            }
            if (null != connection) {
                connection.close();
            }
        }
    }
}